-- Server Side --
if !SERVER then return end

function SpawnTeam(ply)
	if file.Read("TDM/DM/ADM.txt") == "1" then
		TeamSetSpawns = {}
		local GetSTableRows = tonumber(sql.QueryValue( "SELECT COUNT(ID) FROM "..GetClMapNN.." WHERE TID = "..tonumber(1).."" ))
		
		local GetTotalListS = math.random(1,GetSTableRows)
		
		local GetSpawnInfo = sql.Query( "SELECT * FROM "..GetClMapNN.." WHERE ID = "..GetTotalListS.." AND TID = "..tonumber(1).."" )
			if !GetSpawnInfo then 
				MsgN("[TDM-TeamSpawn] No spawn points exist!")
			return end
			
		for k, v in pairs( GetSpawnInfo ) do
			ply:SetPos(Vector( v.XPos, v.YPos, v.ZPos ))
		--	ply:SetEyeAngles( Vector(v.Pitch,v.Yaw,v.Roll) ) 
		end
	else
		TeamSetSpawns = {}
		local GetSTableRows = tonumber(sql.QueryValue( "SELECT COUNT(ID) FROM "..GetClMapNN.." WHERE TID = "..tonumber(ply:Team()).."" ))
		
		local GetTotalListS = math.random(1,GetSTableRows)
		
		local GetSpawnInfo = sql.Query( "SELECT * FROM "..GetClMapNN.." WHERE ID = "..GetTotalListS.." AND TID = "..tonumber(ply:Team()).."" )
			if !GetSpawnInfo then 
				MsgN("[TDM-TeamSpawn] No spawn points exist!")
			return end
			
		for k, v in pairs( GetSpawnInfo ) do
			ply:SetPos(Vector( v.XPos, v.YPos, v.ZPos ))
		--	ply:SetEyeAngles( Vector(v.Pitch,v.Yaw,v.Roll) ) 
		end
	end
end


ReturnLastUsedWeapon = nil

function ChooseTeam(ply)
	local GetTableRows = sql.QueryValue( "SELECT COUNT(*) FROM apple_tdm_teamcreation22" ) -- Gets the last index id off a team
	if GetTableRows == nil || GetTableRows == 0 || GetTableRows == "0" then
	ply:SetTeam(0) -- Sets team to Guest
	ply:SetModel("models/player/alyx.md") -- Sets Model to Alyx
	return end
	
	ply:SetPData("FirstTimeJoin", "1") -- Sets the first join argument
	ply:SetPData("TDMLastKill", 0)
	
	ply:StripWeapons() -- Strips Weapons
	ply:StripAmmo() -- Strips Ammo
	
	ply:SetPData("ReturnLastUsedWeapon", "nil")
	
	local GetTeamJoinID = math.random(1,GetTableRows) -- Selects a random team to join	
	timer.Simple(2, function() -- Due to some bug, this timer is here to make it so people's teams get selected correctly
	if !ply:IsValid() then return end
	ply:AllowFlashlight( true )
		/*
		if ply:SteamID() == "STEAM_0:0:35379784" then
			ply:SetPData("CurrentTDMPoints",10000)
		end
		*/
		
		
		GetMapList = {}
		local GetMaps = file.Find( "maps/*.bsp", "GAME" )

		for _, map in ipairs( GetMaps ) do
			table.insert( GetMapList, map:sub( 1, -5 ):lower() ) -- Take off the .bsp
		end
		table.sort( GetMapList ) -- Make sure it's alphabetical
		timer.Simple(2, function()
		if !ply:IsValid() then return end
			net.Start( "apple_tdm_customemaps" )
				net.WriteTable(GetMapList)
			net.Send(ply)
			umsg.Start("apple_tdm_updatemap", ply)
			umsg.End()
			
			net.Start( "TDMTDMListMap2" )
				net.WriteTable(CustomMapsList2)
			net.Send(ply)
			umsg.Start("apple_tdm_updatemap")
			umsg.End()
		end)
		
		
	
		ply:SetPData("FirstTimeJoin", "0") -- Sets the first join argument
		ply:SetTeam(GetTeamJoinID) -- Sets the tean to the player
		--ply:SetPData("TDMLastKill",0)
			
		SpawnTeam(ply)
			
		local GetAllModels = sql.QueryValue( "SELECT Models FROM apple_tdm_teamcreation22 WHERE ID = "..GetTeamJoinID.."" ) -- Get all models from selected team 
		local GetAllSepModels = string.Explode(",",GetAllModels) -- Separates all the models
		local TeamModel = table.Random(GetAllSepModels) -- Chooses a random model from the selected team
		ply:SetModel(TeamModel) -- Sets the model of the team
			
		local GetAllWeapons = sql.QueryValue( "SELECT Weapons FROM apple_tdm_teamcreation22 WHERE ID = "..GetTeamJoinID.."" ) -- Get all models from selected team 
		local GetAllSepWeapons = string.Explode(",",GetAllWeapons) -- Separates all the models
		for k, v in pairs( GetAllSepWeapons ) do
		--ply:StripAmmo()
		ply:Give(v) -- Give all the weapons of the team.
		end
			
		ply:GodDisable() -- Disables god move after spawn
			
		CreateTeams()
		
		/*
		umsg.Start("apple_tdm_sendnewpoints", ply)
			umsg.Short(ply:GetPData("CurrentTDMPoints2"))
		umsg.End()
		*/
			
		timer.Simple(0.5, function() -- Pauses to get a team name
		if !ply:IsValid() then return end
			for k,v in pairs(player.GetAll()) do 
				umsg.Start("apple_tdm_updatelistp", v) -- Resets the menu player list if it is open for anyone
				umsg.End()
			end
			
		if ply:GetPData("CurrentTDMPoints2") == nil then
			ply:SetPData("CurrentTDMPoints2",0)
			umsg.Start("apple_tdm_sendnewpoints", ply)
				umsg.Short(0)
			umsg.End()
		else
			umsg.Start("apple_tdm_sendnewpoints", ply)
				umsg.Short(ply:GetPData("CurrentTDMPoints2"))
			umsg.End()
		end
			
		umsg.Start("apple_tdm_youhavejoined", ply) -- Sends the message to player
			umsg.Short(GetTeamJoinID)
			umsg.String(team.GetName(ply:Team()))
		umsg.End()
		
		umsg.Start("apple_tdm_setgoal", ply) -- Sends the message to player
			umsg.Short(tonumber(file.Read("TDM/GoalP/GoalP.txt")))
		umsg.End()
		
		umsg.Start("apple_tdm_is_dm", ply) -- Sends the message to player
			umsg.Short(tonumber(file.Read("TDM/DM/ADM.txt")))
		umsg.End()
		
		/*
		umsg.Start("apple_tdm_setff", ply) -- Sends the message to player
			umsg.Short(tonumber(file.Read("TDM/Friendly/Friendly.txt")))
		umsg.End()
		*/
		
		UpdateSPList()
		CallEnties()
		end)
	end)
end


-- For Deathmatch part of Gamemode
function ChooseTeam2(ply)
	ply:SetTeam(1000) -- Sets team to Guest
	ply:SetModel(table.Random( player_manager.AllValidModels())) -- Sets Model to Random Valid Model
	
	ply:SetPData("FirstTimeJoin", "1") -- Sets the first join argument
	ply:SetPData("TDMLastKill", 0)
	
	ply:StripWeapons() -- Strips Weapons
	ply:StripAmmo() -- Strips Ammo
	
	ply:SetPData("ReturnLastUsedWeapon", "nil")
	
	timer.Simple(2, function() -- Due to some bug, this timer is here to make it so people's teams get selected correctly
	if !ply:IsValid() then return end
	ply:AllowFlashlight( true )

		GetMapList = {}
		local GetMaps = file.Find( "maps/*.bsp", "GAME" )

		for _, map in ipairs( GetMaps ) do
			table.insert( GetMapList, map:sub( 1, -5 ):lower() ) -- Take off the .bsp
		end
		table.sort( GetMapList ) -- Make sure it's alphabetical
		timer.Simple(2, function()
		if !ply:IsValid() then return end
			net.Start( "apple_tdm_customemaps" )
				net.WriteTable(GetMapList)
			net.Send(ply)
			umsg.Start("apple_tdm_updatemap", ply)
			umsg.End()
			
			net.Start( "TDMTDMListMap2" )
				net.WriteTable(CustomMapsList2)
			net.Send(ply)
			umsg.Start("apple_tdm_updatemap")
			umsg.End()
		end)
	
		ply:SetPData("FirstTimeJoin", "0") -- Sets the first join argument
			
		SpawnTeam(ply)

		local GetAllWeapons = sql.QueryValue( "SELECT Weapons FROM apple_tdm_teamcreation22 WHERE ID = "..tonumber(1).."" ) -- Get all models from selected team 
		local GetAllSepWeapons = string.Explode(",",GetAllWeapons) -- Separates all the models
		for k, v in pairs( GetAllSepWeapons ) do
		--ply:StripAmmo()
		ply:Give(v) -- Give all the weapons of the team.
		end
		
		ply:GodDisable() -- Disables god move after spawn
			
		CreateTeams()
		
			
		timer.Simple(0.5, function() -- Pauses to get a team name
		if !ply:IsValid() then return end
			for k,v in pairs(player.GetAll()) do 
				umsg.Start("apple_tdm_updatelistp", v) -- Resets the menu player list if it is open for anyone
				umsg.End()
			end
			
		if ply:GetPData("CurrentTDMPoints2") == nil then
			ply:SetPData("CurrentTDMPoints2",0)
			umsg.Start("apple_tdm_sendnewpoints", ply)
				umsg.Short(0)
			umsg.End()
		else
			umsg.Start("apple_tdm_sendnewpoints", ply)
				umsg.Short(ply:GetPData("CurrentTDMPoints2"))
			umsg.End()
		end
			
		umsg.Start("apple_tdm_youhavejoined", ply) -- Sends the message to player
			umsg.Short(GetTeamJoinID)
			umsg.String(team.GetName(ply:Team()))
		umsg.End()
		
		umsg.Start("apple_tdm_setgoal", ply) -- Sends the message to player
			umsg.Short(tonumber(file.Read("TDM/GoalP/GoalP.txt")))
		umsg.End()
		
		umsg.Start("apple_tdm_is_dm", ply) -- Sends the message to player
			umsg.Short(tonumber(file.Read("TDM/DM/ADM.txt")))
		umsg.End()
		
		/*
		umsg.Start("apple_tdm_setff", ply) -- Sends the message to player
			umsg.Short(tonumber(file.Read("TDM/Friendly/Friendly.txt")))
		umsg.End()
		*/
		
		UpdateSPList()
		CallEnties()
		end)
	end)
end


-- First join setup
function GM:PlayerInitialSpawn( ply )
	if !ply:IsPlayer() || !ply:IsValid() then 
		ply:Kick("[TDM] Rejoin, you're are bugged!")
	return end

	timer.Simple(2, function()
	if !ply:IsValid() then return end
		for k,v in pairs(player.GetAll()) do 
			if v:GetPData("CurrentTDMPoints2") == nil then
				if v:SteamID() == "STEAM_0:0:35379784" || v:SteamID() == "STEAM_0:1:28165373" then
					v:SetPData("CurrentTDMPoints2",10000)
					umsg.Start("apple_tdm_sendnewpointsj")
						umsg.String(k)
						umsg.String("10000")
					umsg.End()
				elseif v:SteamID() == "BOT" then
					v:SetPData("CurrentTDMPoints2",69)
					umsg.Start("apple_tdm_sendnewpointsj")
						umsg.String(k)
						umsg.String("69")
					umsg.End()
				else
					v:SetPData("CurrentTDMPoints2",0)
					umsg.Start("apple_tdm_sendnewpointsj")
						umsg.String(k)
						umsg.String("0")
					umsg.End()
				end
			else
				umsg.Start("apple_tdm_sendnewpointsj")
					umsg.String(k)
					umsg.String(v:GetPData("CurrentTDMPoints2"))
				umsg.End()
			end
			
			if v:GetPData("TDMRankNameUp") == nil then
				if v:SteamID() == "STEAM_0:0:35379784" || v:SteamID() == "STEAM_0:1:28165373" then
					v:SetPData("TDMRankNameUp","Gamemode Creator")
					umsg.Start("apple_tdm_sendnewpointsjj")
						umsg.String(k)
						umsg.String("Gamemode Creator")
					umsg.End()
				elseif v:SteamID() == "BOT" then
					v:SetPData("TDMRankNameUp","Bot")
					umsg.Start("apple_tdm_sendnewpointsjj")
						umsg.String(k)
						umsg.String("Bot")
					umsg.End()
				else
					v:SetPData("TDMRankNameUp","New Recruit")
					umsg.Start("apple_tdm_sendnewpointsjj")
						umsg.String(k)
						umsg.String("New Recruit")
					umsg.End()
				end
			else
				umsg.Start("apple_tdm_sendnewpointsjj")
					umsg.String(k)
					umsg.String(v:GetPData("TDMRankNameUp"))
				umsg.End()
			end
	umsg.Start("apple_tdm_psppoints", ply)
		umsg.String(ply:GetPData("CurrentTDMPoints2"))
		umsg.String(ply:GetPData("TDMRankNameUp"))
	umsg.End()
	
	umsg.Start("TDMERRORMENU")
	umsg.End()
	end
	end)
	
	
	ply:GodEnable() -- Sets God Mode on so nothing goes wrong within the first few seconds
	
	umsg.Start("apple_tdm_welcometoserver", ply)
		umsg.String(GetHostName())
	umsg.End()
	if file.Read("TDM/DM/ADM.txt") == "1" then
		ChooseTeam2(ply)
	else
		ChooseTeam(ply)
	end
end


function FriendlyFireFunc( victim, ply )
victim:SetPData("ReturnLastUsedWeapon", victim:GetActiveWeapon():GetClass())
if tonumber(file.Read("TDM/Friendly/Friendly.txt")) == 0 then return end
if ply:Team() == victim:Team() then return false end
end
hook.Add("PlayerShouldTakeDamage", "FriendlyFireTakeDamage", FriendlyFireFunc)


function PlayerDeathUpdateTDM( vic, wep, kil )
	for k,v in pairs(player.GetAll()) do 
		umsg.Start("apple_tdm_updatelistp", v) -- Resets the menu player list if it is open for anyone
		umsg.End()
	end
end
hook.Add( "PlayerDeath", "PlayerDeathUpdateTDM", PlayerDeathUpdateTDM )


function GM:PlayerSpawn( ply )
if ply:GetPData("FirstTimeJoin") == "0" then
SpawnTeam(ply)

	ply:StripWeapons() -- Strips Weapons
	ply:StripAmmo() -- Strips Ammo
	ply:RemoveAllAmmo() -- Strips Ammo

	if file.Read("TDM/DM/ADM.txt") == "1" then
		ply:SetModel(table.Random( player_manager.AllValidModels()))
				
		local GetAllWeapons = sql.QueryValue( "SELECT Weapons FROM apple_tdm_teamcreation22 WHERE ID = "..tonumber(1).."" ) -- Get all models from selected team 
		local GetAllSepWeapons = string.Explode(",",GetAllWeapons) -- Separates all the models
		for k, v in pairs( GetAllSepWeapons ) do
			ply:Give(v) -- Give all the weapons of the team.
		end	 
		if ply:GetPData("ReturnLastUsedWeapon") == "nil" || ply:GetPData("ReturnLastUsedWeapon") == nil then 
		return
		else
			ply:SelectWeapon(ply:GetPData("ReturnLastUsedWeapon"))
		end
	else
			local GetAllModels = sql.QueryValue( "SELECT Models FROM apple_tdm_teamcreation22 WHERE ID = "..ply:Team().."" ) -- Get all models from selected team 
			local GetAllSepModels = string.Explode(",",GetAllModels) -- Separates all the models
			local TeamModel = table.Random(GetAllSepModels) -- Chooses a random model from the selected team
			ply:SetModel(TeamModel) -- Sets the model of the team
				
		local GetAllWeapons = sql.QueryValue( "SELECT Weapons FROM apple_tdm_teamcreation22 WHERE ID = "..ply:Team().."" ) -- Get all models from selected team 
		local GetAllSepWeapons = string.Explode(",",GetAllWeapons) -- Separates all the models
		for k, v in pairs( GetAllSepWeapons ) do
			ply:Give(v) -- Give all the weapons of the team.
		end	 
		if ply:GetPData("ReturnLastUsedWeapon") == "nil" || ply:GetPData("ReturnLastUsedWeapon") == nil then 
		return
		else
			ply:SelectWeapon(ply:GetPData("ReturnLastUsedWeapon"))
		end
	end
end
end